package org.quipu.client.events;

import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;

public class AppEventBus {

    private Map<Class, Set<AppEventListener>> eventListeners = new HashMap<Class, Set<AppEventListener>>();
    private LinkedList<AppEvent> events = new LinkedList<AppEvent>();

    public void addListener(Class eventClass, AppEventListener listener) {
        Set<AppEventListener> listeners = eventListeners.get(eventClass);
        if(listeners == null) {
            listeners = new LinkedHashSet<AppEventListener>();
            eventListeners.put(eventClass, listeners);
        }
        listeners.add(listener);
    }

    public void fireEvent(AppEvent event) {
        events.addLast(event);
        if(events.size() < 2) {
            handleEvents();
        }
    }

    private void handleEvents() {
        AppEvent event;
        while(!events.isEmpty()) {
            event = events.getFirst();
            if(event != null) {
                Class eventClass = event.getClass();
                Collection<AppEventListener> listeners = eventListeners.get(eventClass);
                if(listeners != null) {
                    for(AppEventListener listener : listeners) {
                        listener.handleEvent(event);
                    }
                }
            }
            events.removeFirst();
        }
    }
}
